#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>

#define S_PORT 8080

void chld_handler(int signum){

	while(waitpid(0,NULL,WNOHANG) > 0);
	return ;
}



int main(){

	int i,ret;
	int sfd;
	int cfd;
	socklen_t c_addr_len;
	pid_t pid;
	char buf[BUFSIZ],c_IP[1024];
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;

	//1. socket
	sfd = socket(AF_INET,SOCK_STREAM,0);

	//2. bind	
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(S_PORT);
	s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(sfd,(struct sockaddr *)&s_addr,sizeof(s_addr));

	//3. litsen
	listen(sfd,10);

	//4. aceept
	c_addr_len = sizeof(c_addr);
	while(1){
		cfd = accept(sfd,(struct sockaddr *)&c_addr,&c_addr_len);
		pid = fork();
		if(cfd == -1){
			perror("accept");
			exit(0);
		}
		printf("client ip:%s,port:%d\n",
			inet_ntop(AF_INET,&(c_addr.sin_addr.s_addr),c_IP,sizeof(c_IP)),
			ntohs(c_addr.sin_port));

		if(pid == 0){
			close(sfd);
			break;
		}
		else if(pid > 0){
			close(cfd);
			
			struct sigaction act;

			act.sa_handler = chld_handler;
			sigemptyset(&act.sa_mask);
            		act.sa_flags = 0;

			ret = sigaction(SIGCHLD,&act,NULL);
			if(ret != 0){
				perror("sigaction error");
			}

			continue;
		}
		else{
			perror("pid error");
		}
	}
	if(pid == 0){
		while(1){
			//5. read
			ret = read(cfd,&buf,sizeof(buf));
			write(STDOUT_FILENO, buf, ret);
			//6. toupper
			for(i = 0;i<ret;i++)
				buf[i] = toupper(buf[i]);
			//7. write
			write(cfd,buf,ret);
		}
	}
	return 0;
}
